package com.alibaba.citrus.cr.platform.enhance.functions.company;

import java.util.List;

import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.citrus.cr.platform.enhance.repository.CompanyRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.OrganizationRepository;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.crplatformenhance.enums.CommOperateTypeEnum;
import com.epoch.app.crplatformenhance.enums.OrganizationBizTypeEnum;
import com.epoch.app.crplatformenhance.sdo.CompanySDO;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2021/9/3 20:05
 */
public class CompanyEntity {

    @Getter
    @Setter
    private CompanySDO sdo;

    private static CompanyRepository companyRepository;

    private static OrganizationRepository organizationRepository;

    static {
        companyRepository = SpringContextUtil.getBean(CompanyRepository.class);
        organizationRepository = SpringContextUtil.getBean(OrganizationRepository.class);
    }

    public static CompanyEntity of(CompanySDO sdo) {
        CompanyEntity entity = new CompanyEntity();
        entity.setSdo(sdo);
        return entity;
    }

    public Result<Boolean> doCreate() {
        return companyRepository.createCompany(sdo);
    }

    public Result<Boolean> doEdit() {
        return companyRepository.editCompany(sdo);
    }

    public Result<Boolean> doEnable() {
        sdo.setStatus(CommOperateTypeEnum.ENABLE.getCode());
        return companyRepository.updateCompanyStatus(sdo);
    }

    public Result<Boolean> doDisable() {
        List<OrganizationSDO> organizationList = organizationRepository.getAllOrganizationByBizTypeAndBizId(OrganizationBizTypeEnum.COMPANY.getCode(),sdo.getId());
        if(CollectionUtils.isNotEmpty(organizationList)){
            throw new FunctionException(ErrorMessage.code("OTS-01-003-01-16-008"));
        }
        sdo.setStatus(CommOperateTypeEnum.DISABLE2.getCode());
        return companyRepository.updateCompanyStatus(sdo);
    }

}
